﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mcmurphy.Common;
using TimeTravel.Commons;

namespace TimeTravel.Controllers
{
    /// <summary>
    /// 资源文件请求处理
    /// </summary>
    public class ResourceController : BaseController
    {
        /// <summary>
        /// 处理脚本文件
        /// </summary>
        /// <returns></returns>
        public void Script()
        {
            //原始Url链接
            var rawUri = new Uri(Request.Url.Scheme + "://" + Request.Url.Host + Request.RawUrl);
            //是否压缩参数
            var isCompressJs = rawUri.Query.IndexOf("&compress", StringComparison.OrdinalIgnoreCase) >= 0 
                || rawUri.Query.IndexOf("?compress", StringComparison.OrdinalIgnoreCase) >= 0;
            var queryHref = Request["href"];
            //如果参数为空或者参数中包含有危险字符
            if (string.IsNullOrEmpty(queryHref) || !UrlFilter.FiltUrl(Server.UrlDecode(rawUri.Query)))
            {
                Response.Write("请求参数错误！");
            }
            try
            {
                //请求参数拆分成文件列表
                var jsPaths = PathHelper.QueryToFileList(queryHref, ".js");
                //转成成物理文件列表
                jsPaths = PathHelper.GetPhysicPaths(jsPaths, Request);
                //获取合并后的文件内容（如果标识isCompressJs == true，则需要压缩）
                var finalJsContent = JsCombiner.CombineJs(jsPaths, Server.MapPath("~/"), isCompressJs);
                //替换内容中模板（就简单的替换了一下时间）
                finalJsContent = finalJsContent.Replace("{{now}}", DateTime.Now.ToString("yyyyMMddHHmmss"));
                //输出字节流
                Response.ContentType = "text/javascript";
                Response.BinaryWrite(EncodingHelper.ConvertToUTF8BomEncodingStringBytes(finalJsContent));
                Response.AddHeader("Vary", " Accept-Encoding");
            }
            catch (Exception ex)
            {
                Response.Write(ex.StackTrace);
            }
        }

        /// <summary>
        /// 处理样式文件
        /// </summary>
        /// <returns></returns>
        public void Style()
        {
            var rawUri = new Uri(Request.Url.Scheme + "://" + Request.Url.Host + Request.RawUrl);
            //是否压缩参数
            var isCompressJs = rawUri.Query.IndexOf("&compress", StringComparison.OrdinalIgnoreCase) >= 0
                             || rawUri.Query.IndexOf("?compress", StringComparison.OrdinalIgnoreCase) >= 0;
            var queryHref = Request["href"];
            if (string.IsNullOrEmpty(queryHref) || !UrlFilter.FiltUrl(Server.UrlDecode(rawUri.Query)))
            {
                Response.Write("请求参数错误！");
            }
            try
            {
                //请求参数拆分成文件列表
                var cssPaths = PathHelper.QueryToFileList(queryHref, ".css");
                //转成成物理文件列表
                cssPaths = PathHelper.GetPhysicPaths(cssPaths,Request);
                //获取合并后的文件内容
                var finalCssContent = CssCombiner.CombineAndCompressCss(cssPaths, Server.MapPath("~/"), isCompressJs);
                //输出字节流
                Response.ContentType = "text/css";
                Response.BinaryWrite(EncodingHelper.ConvertToUTF8BomEncodingStringBytes(finalCssContent));
                Response.AddHeader("Vary", " Accept-Encoding");
                
            }
            catch (Exception ex)
            {
                Response.Write(ex.StackTrace);
            }
        }
    }
}
